// pages/initLock/initLock.js
import debounce from "debounce";
import * as MSroomAPI from "../../api/interfaces/MSroom";
import * as EKeyAPI from "../../api/interfaces/key";
import * as LockAPI from "../../api/interfaces/lock";
import { AES_Encrypt } from "../../utils/crypto";

import {
  HttpHandler
} from "../../api/handle/httpHandler";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderList: [],
    pageNo: 1,
    lockList: [],
    state: '开启',
    keyInfo: {}, // 钥匙数据
    specialValueObj: {}, // 智能锁特征值
    isInitLock: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    this.myOrderList();
    this.getTokens()


   

  },
  getTokens() {
    
    if (!wx.getStorageSync('token')) {
      wx.navigateTo({
         url: '/pages/userLogin/userLogin'
       }
     )
   }else {
   MSroomAPI.getToken().then(res => {
      if (res.code == 200) {
        wx.removeStorageSync("access_token"); // 清空当前用户保存的登录状态
        wx.setStorageSync("access_token", AES_Encrypt(res.result));
      }
    })
   }

 
  },
  onReachBottom() {
    this.setData({
      pageNo: this.data.pageNo + 1
    });
    this.myOrderList();
  },
  openLock(e) {

    wx.showLoading();
    let orderNo = e.target.dataset.query.orderNo

    MSroomAPI.openAble(orderNo).then(res => {
      if (res.code == 200) {


        // this.startScan(res.result)
        this.modifyKeyList(res.result)
      } else {
        HttpHandler.handleServerError(res.message);
      }
    }).catch(err => {
      console.log(err)
      HttpHandler.handleServerError(err);
      wx.hideLoading();
    })
  },
  /* 更新电子钥匙列表 */
  modifyKeyList(name) {

    EKeyAPI.list({
      pageNo: 1,
      pageSize: 1000
    }).then(res => {
      if (HttpHandler.isResponseTrue(res)) {


        this.setData({ keyList: res.list });
        let keyItem = {}

        this.data.keyList.forEach(e => {
          if (e.lockAlias == name) {
            keyItem = e

          }
        })


        if (keyItem) {
          this.setData({ keyInfo: keyItem });
          wx.setStorageSync("keyInfo", keyItem);
          //初始化门锁 this.init(keyItem)
          // 直接开锁 
          this.toOpenDoor()
        } else {
          this.startScan(name)
        }
      } else {
        HttpHandler.handleResponseError(res);
      }
    }).catch(err => {
      HttpHandler.handleServerError(err);
    })
  },
  // 开始扫描附近的智能锁设备
  startScan(name) {
    this.data.lockList.splice(0, this.data.lockList.length);
    this.setData({ lockList: this.data.lockList, state: "启动蓝牙设备扫描" });
    HttpHandler.showErrorMsg(`启动蓝牙设备扫描`);
    requirePlugin("myPlugin", ({ startScanBleDevice }: TTLockPlugin) => {
      // 开启蓝牙设备扫描
      startScanBleDevice((lockDevice, lockList) => {
        // TODO 成功扫描到设备
        if (!this.data.isInitLock)
          this.setData({ lockList: lockList, state: "蓝牙设备扫描中" });
        HttpHandler.showErrorMsg(`蓝牙设备扫描中`);
        let keyItem = this.data.lockList.find(v => v.deviceName = name)
        //初始化门锁 
        this.init(keyItem)
        // 直接开锁 
        // this.toOpenDoor()
      }, (err) => {
        HttpHandler.showErrorMsg(`蓝牙扫描开启失败：${err.errorMsg}`);
        wx.hideLoading();
        this.data.lockList.splice(0, this.data.lockList.length);
        this.setData({ lockList: this.data.lockList, state: `蓝牙扫描开启失败：${err.errorMsg}` });
      });
    });
  },
  // 初始化蓝牙设备
  init(e) {//.target.dataset.query
    const lockItem = e;
    this.handleInitLock(lockItem);
  },

  // 初始化智能锁
  handleInitLock: debounce(function (deviceFromScan: TTLockFromScan) {
    if (!deviceFromScan.isSettingMode) {
      this.data.isInitLock = false;
      wx.hideLoading();
      return HttpHandler.showErrorMsg(`智能锁${deviceFromScan.deviceName || deviceFromScan.MAC}已被初始化，当前不可添加`);
    }
    this.data.lockList.splice(0, this.data.lockList.length);
    this.setData({ lockList: this.data.lockList, state: `正在初始化蓝牙智能锁${deviceFromScan.deviceName}, MAC地址：${deviceFromScan.MAC}` });
    HttpHandler.showErrorMsg(`正在初始化蓝牙智能锁${deviceFromScan.deviceName}`);
    requirePlugin("myPlugin", ({ getLockVersion, initLock }: TTLockPlugin) => {
      // 更新智能锁版本信息
      getLockVersion({ deviceFromScan }).then(res => {
        if (res.errorCode == 0) {
          // TODO 更新版本信息成功
          this.setData({ state: "智能锁版本信息已更新，正在初始化设备" });
          HttpHandler.showErrorMsg('智能锁版本信息已更新，正在初始化设备');
          // 调用添加锁接口, serverTime传入服务器时间
          initLock({ deviceFromScan }).then(result => {
            if (result.errorCode == 0) {
              // 设备已成功初始化，请调用开放平台接口上传lockData
              this.setData({ state: "设备已成功初始化，正在调用开放平台接口上传锁数据" });
              HttpHandler.showErrorMsg('设备已成功初始化，正在调用开放平台接口上传锁数据');
              LockAPI.initialize({ lockData: result.lockData }).then(res => {
                if (HttpHandler.isResponseTrue(res)) {
                  this.setData({ isInitLock: false });
                  HttpHandler.showErrorMsg("智能锁已添加");
                  this.modifyKeyList(deviceFromScan.deviceName)
                } else {
                  HttpHandler.handleResponseError(res);
                  this.handleResetLock(result.lockData);
                }
              }).catch(err => {
                HttpHandler.handleServerError(err);
                this.handleResetLock(result.lockData);
              })
            }
          })
        }
      });
    });
  }, 100),
  // 重置智能锁
  handleResetLock: debounce(function (lockData: string) {
    requirePlugin("myPlugin", ({ resetLock }: TTLockPlugin) => {
      // 重置智能锁
      resetLock({ lockData }).then(res => {
        if (res.errorCode == 0) {
          this.setData({ isInitLock: false, state: "初始化智能锁失败，智能锁已重置" })
          HttpHandler.showErrorMsg("初始化智能锁失败，智能锁已重置");
        } else {
          this.setData({ isInitLock: false, state: `智能锁重置失败，请长按重置键进行设备重置：${res.errorMsg}` })
          HttpHandler.showErrorMsg(`智能锁重置失败，请长按重置键进行设备重置：${res.errorMsg}`)
        }
      });
    });
  }, 100),
  // 点击开锁
  toOpenDoor: debounce(function () {
    const ekeyInfo = this.data.keyInfo as IEKeyAPI.List.EKeyInfo;

    wx.showLoading({ title: "正在开锁" });
    requirePlugin("myPlugin", ({ controlLock }: TTLockPlugin) => {
      const start = Date.now();
      // 控制智能锁
      controlLock({
        /* 控制智能锁方式 3 -开锁, 6 -闭锁 */
        controlAction: 3,
        lockData: ekeyInfo.lockData,
        serverTime: Date.now(),
      }).then(res => {
        console.log(res)
        wx.hideLoading();
        if (res.errorCode == 0) {
          wx.showToast({ icon: "success", title: "已开锁" });
        } else {
          HttpHandler.showErrorMsg(`开锁失败: ${res.errorMsg}`);
          this.setData({ state: `开锁失败: ${res.errorMsg}` });
          wx.hideLoading();
        }
      })
    });
  }, 100),
  skip(e) {
    console.log(e)
    wx.navigateTo({
      url: "../authentication/authentication?orderNo=" + e.target.dataset.query.orderNo + '&name=' + e.target.dataset.query.name,
    })
  },
  /* 订单列表 */
  myOrderList() {
    MSroomAPI.myOrder({
      pageNo: this.data.pageNo,
      pageSize: 20
    }).then(res => {
      if (res.code == 200) {
        if (this.data.pageNo == 1) {
          this.data.orderList.splice(0, this.data.orderList.length, ...res.result.records);
        } else {
          res.result.records.forEach(item => this.data.orderList.push(item));
        }
        this.data.orderList.forEach(e => {
          e.hotelCover = 'https://lyms.imsdx.net/lyms/' + e.hotelCover.split(',')[0]
        });

        this.setData({
          orderList: this.data.orderList
        });

        wx.stopPullDownRefresh();
      } else {
        HttpHandler.handleServerError(res.message);
      }
      wx.hideLoading();
    }).catch(err => {
      console.log(err)
      HttpHandler.handleServerError(err);
      wx.hideLoading();
    })
  },
})